<template>
	<el-card class="box-card">
		<el-form ref="queryForm" :model="query" :inline="true">
			<el-form-item label="用户名称" prop="account">
				<el-input v-model="query.account" placeholder="请输入用户名称" clearable @keyup.enter.native="handleQuery(1)" />
			</el-form-item>
			<el-form-item label="状态" prop="status">
				<el-select v-model="query.status" placeholder="全部" clearable @change="handleQuery(1)">
					<el-option label="启用" :value="1" />
					<el-option label="禁用" :value="2" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" @click="handleQuery(1)">搜索</el-button>
				<el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb20">
			<el-col :span="1.5">
				<el-button v-hasPermi="['/user/register']" type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        <!-- <el-button :disabled="!ids.length" type="danger" icon="el-icon-delete" @click="handleDelete()">删除</el-button> -->
        <!-- <el-button type="info" icon="el-icon-upload2">导入</el-button>
        <el-button type="warning" icon="el-icon-download">导出</el-button> -->
			</el-col>
		</el-row>

		<el-card class="box-card">
			<el-table v-loading="listLoading" :data="dataList" border @selection-change="handleSelectionChange">
				<!-- <el-table-column type="selection" width="50" :selectable="row => row.id!==1" align="center" /> -->
				<el-table-column prop="account" label="用户名" show-overflow-tooltip width="200" />
				<el-table-column prop="name" label="姓名" show-overflow-tooltip width="200" />
				<el-table-column prop="mobile" label="手机号" show-overflow-tooltip width="200" />
				<el-table-column prop="status" label="状态" width="80">
					<template slot-scope="{row}">
						<el-switch v-hasPermi="['/user/update']" :disabled="row.id===1" :value="row.status" :active-value="1" :inactive-value="2" @change="switchChange($event, row.id)" />
					</template>
				</el-table-column>
				<el-table-column label="创建时间" align="center" prop="ctime">
					<template slot-scope="scope">
						<span>{{ scope.row.ctime | parseTime }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
					<template v-if="row.id!==1" slot-scope="{row}">
						<el-button v-hasPermi="['/user/update']" type="text" @click="handleUpdate(row.id)">编辑</el-button>
						<el-button v-hasPermi="['/user/updateRolesFromUser', '/user/roles/*']" type="text" @click="handleUpdate(row.id, 'role')">分配角色</el-button>
						<el-button v-hasPermi="['/user/modifyPassword']" type="text" @click="handleUpdate(row.id, 'passwd')">修改密码</el-button>
						<el-button v-hasPermi="['/user/delete/*']" type="text" @click="handleDelete(row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<pagination v-show="total>0" :total="total" :page.sync="query.pageNum" :limit.sync="query.pageSize" @pagination="handleQuery" />
		</el-card>

		<!-- 添加或修改用户 -->
		<el-dialog :title="(formModel.id?'编辑':'新增')+'用户'" :visible.sync="formVisible" width="600px" append-to-body>
			<el-form ref="formModel" :model="formModel" :rules="formRules" label-width="80px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="账号" prop="account">
							<el-input v-model="formModel.account" placeholder="请输入账号" maxlength="12" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="密码" prop="passwd">
							<el-input :disabled="!!formModel.id" type="password" v-model="formModel.passwd" placeholder="请输入密码" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="姓名" prop="name">
							<el-input v-model="formModel.name" placeholder="请输入姓名" maxlength="10" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="手机号码" prop="mobile">
							<el-input v-model="formModel.mobile" placeholder="请输入手机号码" maxlength="11" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="状态">
							<el-switch v-model="formModel.status" :active-value="1" :inactive-value="2" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="formVisible=!formVisible;reset;">取 消</el-button>
				<el-button :loading="submitLoading" type="primary" @click="submitForm">确 定</el-button>
			</div>
		</el-dialog>
		<!-- 修改密码 -->
		<el-dialog title="修改密码" :visible.sync="passwdVisible" width="600px" append-to-body>
			<el-form ref="passwdModel" :model="passwdModel" :rules="passwdRules" label-width="80px">
        <el-form-item label="新密码" prop="newPassword">
          <el-input type="password" v-model="passwdModel.newPassword" placeholder="请输入新密码" maxlength="20" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input type="password" v-model="passwdModel.confirmPassword" placeholder="请输入确认密码" maxlength="20" />
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="passwdVisible=!passwdVisible;resetPass;">取 消</el-button>
				<el-button :loading="submitPassLoading" type="primary" @click="submitPassForm">确 定</el-button>
			</div>
		</el-dialog>
		<!-- 分配角色 -->
		<el-dialog title="分配角色" :visible.sync="roleVisible" width="600px" append-to-body>
      <div>
        <el-checkbox :value="roleList.length===roleModel.roleIds.length?1:0" :true-label="1" :false-label="0" @change="handleCheckedAll">全选/全不选</el-checkbox>
        <div class="mt10 checkbox-custom">
          <el-checkbox-group v-model="roleModel.roleIds" size="small">
            <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id" border>{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="roleVisible=!roleVisible;">取 消</el-button>
				<el-button :loading="submitRoleLoading" type="primary" @click="submitRoleForm">确 定</el-button>
			</div>
		</el-dialog>
	</el-card>
</template>

<script>
import { roleListPage } from '@/api/system/role'
import { userListPage, userGetId, userDeleteId,
  userDeleteBatch, userRegister, userUpdate,
  userModifyPassword, getUserRolesId, userUpdateRolesFromUser } from '@/api/system/user'

export default {
  data () {
    return {
      // 列表数据
      query: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      dataList: null,
      listLoading: false,
      ids: [],
      // 新增/编辑用户
      formVisible: false,
      submitLoading: false,
      formModel: {
        status: 1
      },
      formRules: {
        account: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        passwd: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: '用户密码长度必须介于 6 和 20 之间', trigger: 'blur' }
        ],
        // mobile: [
        //   {
        //     pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        //     message: "请输入正确的手机号码",
        //     trigger: "blur"
        //   }
        // ]
      },
      // 修改密码
      passwdVisible: false,
      submitPassLoading: false,
      passwdModel: {},
      passwdRules: {
        newPassword: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: '新密码长度必须介于 6 和 20 之间', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: '确认密码长度必须介于 6 和 20 之间', trigger: 'blur' },
          { required: true,
            validator: (rule, value, callback) => {
              if (this.passwdModel.newPassword !== value) {
                callback(new Error('两次密码输入不一致'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ]
      },
      // 分配权限
      roleVisible: false,
      submitRoleLoading: false,
      roleModel: {
        roleIds: []
      },
      roleList: []
    }
  },
  created () {
    this.handleQuery()
    this.getRoleListPage()
  },
  methods: {
    // 获取筛选信息
    getRoleListPage () {
      roleListPage({pageNum: -1}).then(res => {
        const { records } = res.data
        this.roleList = records
      })
    },
    // 全选/全不选
    handleCheckedAll() {
      if (this.roleList.length===this.roleModel.roleIds.length) {
        this.$set(this.roleModel, 'roleIds', [])
      } else {
        this.$set(this.roleModel, 'roleIds', this.roleList.map(o => o.id))
      }
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
    },
    // 用户列表
    handleQuery (pageNum) {
      if (pageNum===1) this.query.pageNum = 1
      this.listLoading = true
      userListPage(this.query).then(res => {
        const { records, total } = res.data
        this.dataList = records
        this.total = total
        this.listLoading = false
      }).catch(err => {
        if (err.code === -103) {
          this.$router.push('/403')
        }
        this.listLoading = false
      })
    },
    // 重置
    resetQuery () {
      this.resetForm('queryForm')
      this.handleQuery(1)
    },
    // 新增
    handleAdd () {
      this.reset()
      this.formVisible = !this.formVisible
    },
    // 修改/分配角色/修改密码
    handleUpdate (id, type = 'edit') {
      if (type === 'passwd') {
        this.passwdModel = { id }
        this.passwdVisible = !this.passwdVisible
        return
      }
      if (type === 'role') {
        this.$set(this.roleModel, 'roleIds', [])
        getUserRolesId(id).then(res => {
          const roleIds = res.data.map(o => o.id)
          this.roleModel = { id, roleIds }
        })
        this.roleVisible = !this.roleVisible
        return
      }
      this.handleAdd()
      userGetId(id).then(res => {
        this.formModel = { ...res.data, passwd: '666666' }
      })
    },
    // 删除
    handleDelete (id) {
      if (id) {
        this.$confirm(`请确认是否要删除该用户?`, { type: 'warning' }).then(() => {
          userDeleteId(id).then(() => {
            this.$message.success('删除成功')
            this.handleQuery()
          })
        })
      } else {
        this.$confirm(`请确认是否要删除该批用户?`, { type: 'warning' }).then(() => {
          userDeleteBatch(this.ids).then(() => {
            this.$message.success('删除成功')
            this.handleQuery()
          })
        })
      }
    },
    // 提交分配得角色
    submitRoleForm(){
      this.submitRoleLoading = true
      userUpdateRolesFromUser(this.roleModel).then(() => {
        this.$message.success('添加成功')
        this.roleModel = { roleIds: [] }
        this.roleVisible = !this.roleVisible
      })
      this.submitRoleLoading = false
    },
    // 新增/编辑
    submitForm () {
      this.submitLoading = true
      this.$refs["formModel"].validate(async valid => {
        if (valid) {
          try {
            if (this.formModel.id) {
              await userUpdate({ ...this.formModel, passwd: '' })
              this.$message.success('修改成功')
            } else {
              await userRegister(this.formModel)
              this.$message.success('新增成功')
            }
            this.formVisible = !this.formVisible
            this.handleQuery()
            this.submitLoading = false
          } catch (error) {
            this.submitLoading = false
          }
        } else {
          this.submitLoading = false
        }
      })
    },
    // 提交修改得密码
    submitPassForm(){
      this.submitPassLoading = true
      this.$refs["passwdModel"].validate(async valid => {
        if (valid) {
          try {
            await userModifyPassword(this.passwdModel)
            this.$message.success('修改成功')
            this.passwdVisible = !this.passwdVisible
            this.handleQuery()
            this.submitPassLoading = false
          } catch (error) {
            this.submitPassLoading = false
          }
        } else {
          this.submitPassLoading = false
        }
      })
    },
    // 表单重置
    reset () {
      this.formModel = {
        status: 1
      }
      this.resetForm("formModel")
    },
    // 密码重置
    resetPass () {
      this.passwdModel = {}
      this.resetForm("passwdModel")
    },
    // 状态变更
    switchChange (status, id) {
      this.$confirm(`请确认是否要${status === 2 ? '禁用' : '启用'}该用户?`, { type: 'warning' }).then(() => {
        userUpdate({ id, status }).then(() => {
          this.handleQuery()
        })
      })
    }
  }
}
</script>
